<?php
class MeetingModel extends Model{

    private $init_data; //预留字段

	private $meeting_details_cows="a.`meeting_id`,a.`meeting_type`,a.`meeting_title`,a.`meeting_sponsorsId`,b.audience_name as `meeting_sponsorsName`,b.audience_portrait,a.`meeting_description`,a.`meeting_startTime`,a.`meeting_endTime`,a.`meeting_local`,a.`time_insert`,a.`meeting_state`,a.`meeting_room_id`,c.room_name,d.floor_name,e.building_name,f.local_name";
	private $meeting_details_cows_new="a.`meeting_id`,a.`meeting_type`,a.`meeting_title`,a.`meeting_sponsorsId`,b.audience_name as `meeting_sponsorsName`,b.audience_portrait,a.`meeting_description`,a.`meeting_startTime`,a.`meeting_endTime`,a.`meeting_local`,a.`time_insert`,a.`meeting_state`,a.`meeting_room_id`";
	private $meeting_join_cows="b.`audience_id`,b.`audience_name`,a.`join_state`,b.`audience_portrait`,a.`join_content`";
	private $meeting_id="a.`meeting_id`";
	private $meeting_list_cows="a.`meeting_id`,a.`meeting_type`, a.`meeting_title`, a.`meeting_sponsorsId`, a.`meeting_description`, a.`meeting_startTime`, a.`meeting_endTime`, a.`meeting_local`, a.`time_insert`,b.audience_name as meeting_sponsorsName,b.audience_portrait,a.`meeting_state`,room_name,floor_name,building_name,local_name";
	private $meeting_list_cows_uid="a.`meeting_id`,a.`meeting_type`, a.`meeting_title`, a.`meeting_sponsorsId`, a.`meeting_description`, a.`meeting_startTime`, a.`meeting_endTime`, a.`meeting_local`, a.`time_insert`,d.audience_name as meeting_sponsorsName,d.audience_portrait,a.`meeting_state`,room_name,floor_name,building_name,local_name";
	private $search_type=array(0=>'主题',1=>'发起人',3=>'date',4=>'month');
	//新添加
	private $meeting_list_cows_new = 'a.meeting_id,a.meeting_local,a.`meeting_type`,a.meeting_title, a.`meeting_sponsorsId`, a.meeting_startTime,a.meeting_endTime,meeting_state,"" as room_name,"" as floor_name,"" as building_name,"" as local_name';
/**
 * 获取个人会议列表 [no paging]
 * use by A('Meeting')->get_meeting_calendar_list
 * create by zhanghao in 2014/11/29 11:30
 */
	public function get_meeting_calendar_list($data){
		$user_group = D('Audience')->get_user_meeting_group($data['uid']);

		//查询我参加的所有会议信息
		$sql = 'select a.meeting_date,a.meeting_type from meeting a';
		$sql.= ' join meeting_join f on a.meeting_id = f.meeting_id';
		$sql.= ' where audience_id='.$data['uid'].' and meeting_category in ('.$user_group.') and meeting_endTime>='. (time()-2592000);

		$rs=M('meeting','','DB_MEETING')->query($sql);
        //排序
        $new_arr=array();
		foreach($rs as $val){
			if( $new_arr[$val['meeting_date']] === NULL )
				$new_arr[$val['meeting_date']] = $val['meeting_type'];
			else
                $new_arr[$val['meeting_date']] < $val['meeting_type'] && $new_arr[$val['meeting_date']] = $val['meeting_type'];
		}
		ksort($new_arr);
		foreach($new_arr as $key=>$val){
			$new_arr1[]=array($key,$val);	
		}
		return $new_arr1;
	}
/*
 * 获取会议列表
 * use by A('Meeting')->check_idle_meeting_room
 * create by zhanghao 2014-11-17 10:58
 * */
    public function get_meeting_list($data){

		$user_group = D('Audience')->get_user_meeting_group($data['uid']);

        $sql = 'select '.$this->meeting_list_cows_new.' from meeting a';
        switch($data['type']){
            case 1://发起
                $sql.= ' where a.meeting_sponsorsId='.$data['uid'].' and meeting_category in ('.$user_group.')';
                break;
            case 2://待确认
                $sql.= ' join meeting_join f on a.meeting_id = f.meeting_id';
                $sql.= ' where audience_id='.$data['uid'];
                $sql.= ' and meeting_category in ('.$user_group.') and meeting_endTime>='.(time()-2592000);
				$sql.= ' union '.'select '.$this->meeting_list_cows_new.' from meeting as a where meeting_join_type=1';
				break;
        }
        $sql.= ' order by `meeting_startTime` desc';
        $sql.= ' limit '.(($data['page']-1)*$_REQUEST['count']).','.$data['count'];
        return M('meeting','','DB_MEETING')->query($sql);
    }
/**
  *搜索会议
  *update author: zhanghao
  *update time  : 2014-11-19 11:22
  *use    this	: A('Meeting')->search_meeting
  ****************************************/	
	public function search_meeting($data){
		switch($data['searchType']){
			case 1:$cow='d.`audience_name`';break;
			case 2:$cow='a.`meeting_title`';break;
			//case 3:$cow='c.`type_name`';break;
			default:
				$cow='d.`audience_name`';break;
		}
		if($data['conditions']!=''){
			$where = '  and INSTR ('.$cow.',"'.$data['conditions'].'")';
		}else{
			$where='';	
		}
		if($data['searchType']==3){
			$startTime=strtotime($data['conditions'].' 00:00:00');
			$endTime  =strtotime($data['conditions'].' 23:59:59');
			$where=' and a.meeting_startTime>='.$startTime.' and a.meeting_endTime<='.$endTime;
		}else if($data['searchType']==4){
			$date=explode('-',$data['conditions']);
			$startTime = strtotime($date[0].'-'.$date[1].'-'.'01 00:00:00');
			if($date[1]==12){
				$date[0]=(int)$date[0]+1;
				$date[1]='01';
			}else{
				$date[1]=(int)$date[1]+1;
			}
			$endTime = strtotime($date[0].'-'.$date[1].'-'.'01 00:00:00');
			$where=' and a.meeting_startTime>='.$startTime.' and a.meeting_endTime<'.$endTime;
		}
		
		if($data["uid"]!=''){
			$sql = "select ".$this->meeting_list_cows_uid.",c.join_state from meeting_join c";
			$sql.= " join meeting a on a.meeting_id=c.meeting_id";
			$sql.= " join audience b on c.audience_id=b.audience_id";
			$sql.= " join audience d on a.meeting_sponsorsId=d.audience_id";
			$sql.= ' join meeting_room f on a.meeting_room_id=f.room_id';
			$sql.= ' join meeting_roomfloor g on f.floor_id=g.floor_id';
			$sql.= ' join meeting_roombuilding h on g.building_id=h.building_id';
			$sql.= ' join meeting_roomlocal i on h.local_id=i.local_id';
			$sql.= " where c.audience_id=".$data['uid'].$where;
			$sql.= " order by a.`meeting_startTime` desc";
			$sql.= " limit ".(($data['page']-1)*$_REQUEST['count']).",".$data['count'];
		}else{
			$sql = "select ".$this->meeting_list_cows." from meeting as a";
			$sql.= " join audience as b on a.meeting_sponsorsId=b.audience_id";
			$sql.= ' join meeting_room f on a.meeting_room_id=f.room_id';
			$sql.= ' join meeting_roomfloor g on f.floor_id=g.floor_id';
			$sql.= ' join meeting_roombuilding h on g.building_id=h.building_id';
			$sql.= ' join meeting_roomlocal i on h.local_id=i.local_id';
			$sql.= ' where 1=1'.$where;
			$sql.= " order by ".$this->meeting_id." desc";
			$sql.= " limit ".(($data['page']-1)*$_REQUEST['count']).",".$data['count'];	
		}
		$rs=M("meeting","",'DB_MEETING')->query($sql);
		return $rs;
	}
	
	//创建会议
    //这里推送给
	public function create_meeting($data){
		$data['meeting_sponsorsId']=$data['uid'];
		$data['meeting_date']=date('Y-m-d',$data['meeting_startTime']);
		$rs=M('meeting','','DB_MEETING')->add($data);
		if($rs){
			$arr=explode(',',$data['meeting_join']);
			foreach($arr as $val){
				$newdata['meeting_id']=$rs;
				$newdata['audience_id']=$val;
				$newdata['join_state']=0;
				M('meeting_join','','DB_MEETING')->add($newdata);
			}
			return $rs;
		}else{
			return false;	
		}
	}
    //use by A('Meeting')->update_meeting_info
	public function update_meeting_info($data){
        if($data['meeting_startTime']!='')
		    $data['meeting_date']=date('Y-m-d',$data['meeting_startTime']);
        if($data['meeting_join']!=''){
            M('meeting_join','','DB_MEETING')->where('meeting_id='.$data['meeting_id'])->delete();
            $arr=explode(',',$data['meeting_join']);
            foreach($arr as $val){
                $newdata['meeting_id']=$data['meeting_id'];
                $newdata['audience_id']=$val;
                $newdata['join_state']=0;
                M('meeting_join','','DB_MEETING')->add($newdata);
            }
            unset($val);
        }
        if($data['startTime']!='' && $data['endTime']!=''){

        }
        return M('meeting','','DB_MEETING')->where('meeting_id='.$data['meeting_id'])->save($data);
	}
	
	//根据会议id获取会议相关信息
	public function get_meeting_by_id($id){

		$meeting_details_cows="`meeting_id`,`meeting_category`,`meeting_type`,`meeting_title`,`meeting_sponsorsId`,'meeting_local_type',`meeting_description`,`meeting_startTime`,`meeting_endTime`,`meeting_local`,`time_insert`,`meeting_state`,`meeting_room_id`";

		$rs = M('meeting','','DB_MEETING')->field($meeting_details_cows)->where('meeting_id='.$id)->find();
		if(!$rs)
			return false;
		
		$category = M('meeting_category','','DB_MEETING')->where('category_id='.$rs['meeting_category'])->getField('category_name');
		$rs['meeting_category'] = $category ? $category : '普通会议';

		$audience = M('audience','','DB_MEETING')->field('audience_name,audience_portrait')->where('audience_id='.$rs['meeting_sponsorsId'])->find();
		if($audience){
			$rs['meeting_sponsorsName'] = $audience['audience_name'];
			$rs['audience_portrait']	= $audience['audience_portrait'];
		}else{
			$rs['meeting_sponsorsName'] = 'admin';
			$rs['audience_portrait']	= '';
		}

		$rs['room_name'] = '';
		$rs['floor_name']= '';
		$rs['building_name']='';
		$rs['local_name'] = '';

		return $rs;
	}
	//查询会议的参会人
	public function get_meeting_join($id){
		$type = M('meeting','','DB_MEETING')->where('meeting_id='.$id)->getField('meeting_join_type');
		if($type==2){
			$psql = "select ".$this->meeting_join_cows." from `meeting_join` as a";
			$psql.= " join audience as b on a.audience_id=b.audience_id";
			$psql.= " join meeting c on a.meeting_id=c.meeting_id";
			$psql.= " where a.meeting_id=".$id;
			$psql.= " and c.meeting_sponsorsId!=a.audience_id";
			$rs1  = M("meeting_join","",'DB_MEETING')->query($psql);
		}else{
			$cows = "`audience_id`,`audience_name`,'0' as `join_state`,`audience_portrait`,'' as `join_content`";
			$rs1 = M("audience","",'DB_MEETING')->field($cows)->select();
		}
		return $rs1;
	}
	//获取会议信息
	public function check_idle_meeting_room_by_uid($data){
		//1.通过uid获取当前用户的部门信息
		$department	 = D('Department')->get_department_by_uid($data['uid']);
		$re['local_id']=$department['local_id'];
		$re['building_id']=$department['building_id'];
		$re['floor_id']=$department['floor_id'];
		//查询相关楼层信息
		$re['locals'] = $this->get_meeting_room_local();
		$re['buildings'] = $this->get_meeting_room_building($re['local_id']);
		$re['floors'] = $this->get_meeting_room_floor($re['building_id']);
		//查询符合条件的meeting_room
		$sql ='select room_id,room_name from meeting_room';
		$sql.=' where floor_id='.$department['floor_id'];
		$rs=M('meeting_room','','DB_MEETING')->query($sql);
		foreach($rs as $val){
			$sql ='select schedule_id from meeting_room_schedule';
			$sql.=' where room_id='.$val['room_id'];
			$sql.=' and schedule_startTime>='.$data['meeting_startTime'];
			$sql.=' and schedule_endTime<='.$data['meeting_endTime'];
			$rs=M('meeting_roomSchedule','','DB_MEETING')->query($sql);
			if(!$rs)
				$new[]=$val;
		}
		$re['meeting_room']=$new;
		return $re;	
	}
	
/**
  *查询会议室
  *update author: zhanghao
  *update time  : 2014-11-12 15:40
  *use    this	: A('Meeting')->check_idle_meeting_room
  ****************************************/	
	public function check_idle_meeting_room($data){
		$data['meeting_date']	= $data['meeting_date']==NULL?date('Y-m-d'):$data['meeting_date'];
		//$data['count']		= $data['count']==NULL?10:$data['count'];
		//$data['page']			= $data['page']==NULL?1:$data['page'];
		
		$sql = 'select * from meeting_room as b';
		$sql.= ' join meeting_roomfloor c on b.floor_id=c.floor_id';
		$sql.= ' join meeting_roombuilding d on c.building_id=d.building_id';
		$sql.= ' join meeting_roomlocal e on d.local_id=e.local_id';
		if($data['floor_id']!='')
			$sql.= ' where b.floor_id='.$data['floor_id'];
		$rs	 = M('meeting_room','','DB_MEETING')->query($sql);
		if(!$rs)
			return false;
		
		foreach($rs as $val){
			$sql1 ='select * from meeting_roomschedule';
			$sql1.=' where room_id='.$val['room_id'].' and schedule_date="'.$data['meeting_date'].'"';
			$sql1.=' limit 1';
			$schedule=M('meeting_roomschedule','','DB_MEETING')->query($sql1);
			if($schedule){
				if($data['maxstep']!=''){
					if($data['maxstep']>$schedule['schedule_maxstep'])
					continue;
				}
				$val['have_schedule']	=true;
				$val['schedule_states']	=$schedule;
			}else{
				$val['have_schedule']=false;
				$val['schedule_states']=false;
			}
            $re = $this->get_current_day_schedule_time($val['room_id'],$data['meeting_date']);

            if($re){
                //uasort($re,'sort_meeting_startTime');
                $val['schedule_time'] = $re;
            }else
                $val['schedule_time'] = null;
			$arr[]=$val;
		}
		return $arr;
	}

//use by this->check_idle_meeting_room
    public function get_current_day_schedule_time($room_id,$meeting_date)
    {
        $sql = 'select meeting_startTime,meeting_endTime,meeting_title from meeting where meeting_room_id='.$room_id.' and meeting_date="'.$meeting_date.'" order by meeting_startTime';
        return M('meeting','','DB_MEETING')->query($sql);
    }
	
	//获取所有的地区信息
	public function get_meeting_room_local(){
		return M('meeting_room_local','','DB_MEETING')->query('SELECT * FROM  `meeting_room_local`');
	}
	//获取所有的楼座信息
	public function get_meeting_room_building($local){
		return M('meeting_room_building','','DB_MEETING')->query('SELECT * FROM  `meeting_room_building` where local_id='.$local); 	
	}
	//获取所有的楼层信息
	public function get_meeting_room_floor($building){
		return M('meeting_room_floor','','DB_MEETING')->query('SELECT * FROM  `meeting_room_floor` where building_id='.$building); 	
	}
	
	//通知所有人取消会议
	public function cancel_meeting($id){
		$data['meeting_state']=0;
		//删除会议室预定
		M('meeting_roomSchedule','','DB_MEETING')->where('meeting_id='.$id)->delete();
		//取消会议
		$sql = 'update `meeting` set meeting_state=0 where meeting_id='.$id;
		return M('meeting','','DB_MEETING')->execute($sql);	
	}

	//修改参会状态
	public function update_join_state($data){
		return M('meeting_join','','DB_MEETING')->where('meeting_id='.$data['meeting_id'].' and audience_id='.$data['uid'])->save($data);
	}
/**
  *获取所有楼层
  *update author: zhanghao
  *update time  : 2014-11-10 09:52
  *use    this	: A('Meeting')->get_meeting_room_locals
  ****************************************/
  	public function get_all_floor(){
		return M('meeting_roomfloor','','DB_MEETING')->select();
	}
/**
  *获取所有地区
  *update author: zhanghao
  *update time  : 2014-11-10 09:52
  *use    this	: A('Meeting')->get_meeting_room_locals
  ****************************************/	
	public function get_all_local(){
		return M('meeting_roomlocal','','DB_MEETING')->select();
	}
/**
  *获取所有大楼
  *update author: zhanghao
  *update time  : 2014-11-10 09:52
  *use    this	: A('Meeting')->get_meeting_room_locals
  ****************************************/	
	public function get_all_building(){
		return M('meeting_roombuilding','','DB_MEETING')->select();
	}
/**
  *预定会议室
  *update author: zhanghao
  *update time  : 2014-11-28 11:28
  *use    this	: A('Meeting')->create_meeting
  ****************************************/	
	public function schedule_meeting_room($data){
		$data['room_id']= $data['meeting_room_id'];
		$data['meeting_startTime'];
		$data['meeting_endTime'];

		//first 查询当前所有有关room_id的预定
		$rs = M('meeting','','DB_MEETING')->field('meeting_startTime,meeting_endTime')->where('meeting_room_id='.$data['meeting_room_id'].' and meeting_endTime>'.time())->select();

		foreach($rs as $val)
		{

			if($data['meeting_startTime'] > $val['meeting_startTime'] && $data['meeting_startTime'] < $val['meeting_endTime'])
			{
				//当前开始时间已经预定
				return false;
			}else if($data['meeting_endTime'] > $val['meeting_startTime'] && $data['meeting_startTime'] < $val['meeting_endTime'])
			{
				//当前结束时间已经预定
				return false;
			}else if($val['meeting_startTime'] < $data['meeting_endTime'] && $val['meeting_startTime'] > $data['meeting_startTime'] )
			{
				//有一个会议在 预定的的会议中间
				return false;
			}else if($val['meeting_endTime'] > $data['meeting_startTime'] && $val['meeting_endTime'] < $data['meeting_endTime'] )
			{
				//有一个会议在 预定的的会议中间
				return false;
			}

		}



		/*
		 * //init shedule time
		$data['room_id']= $data['meeting_room_id'];
		$start 			= $this->init_nums(date('H:i',$data['meeting_startTime']));
		$end	 		= $this->init_nums(date('H:i',$data['meeting_endTime']));

		//find room shedule info
		$sql ='select * from meeting_roomschedule';
		$sql.=' where schedule_date="'.$data['schedule_date'].'"';
		$sql.=' and room_id='.$data['meeting_room_id'];
		$sql.=' limit 1';
		$rs = M('meeting_roomschedule','','DB_MEETING')->query($sql);
		if($rs[0]){
			//select if it sheduled
			for($i=$start;$i<=$end;$i++){
				if($rs[0]['schedule_'.$i]==1)
					return false;
			}
			for($i=$start;$i<=$end;$i++){
				$data['schedule_'.$i]=1;
			}
			$rs=M('meeting_roomschedule','','DB_MEETING')->where('schedule_id='.$rs[0]['schedule_id'])->save($data);
			//update max time step
			$this->upt_max_step($rs[0]['schedule_id']);
			return $rs;
		}
		for($i=$start;$i<=$end;$i++){
			$data['schedule_'.$i]=1;
		}
		//update max time step
		$rs=M('meeting_roomschedule','','DB_MEETING')->add($data);
		$this->upt_max_step($rs);
		return $rs;*/
	}
/**
  *预定会议室
  *update author: zhanghao
  *update time  : 2014-11-28 11:28
  *use    this	: A('Meeting')->create_meeting
  ****************************************/
	public function upt_max_step($id){
	   	$sql ='select * from meeting_roomschedule';
		$sql.=' where schedule_id='.$id;
		$sql.=' limit 1';
		$rs = M('meeting_roomschedule','','DB_MEETING')->query($sql);
		
		for($i=0;$i<=23;$i++){
			$data[]=$rs[0]['schedule_'.$i];
		}
		$j=0;
		$y=0;
		$maxtimes=array(0);
		foreach($data as $key=>$value){
			//重复1次
			if($value===0)
				$j++;
			//当前上一个值
			$i=$data[$key-1];
			if($i===NULL)
				continue;
			//如果当前和上一个相同
			if($i===$value){
				//重复次数加1
				$y++;
			}else{
				$maxtimes[]=$y;
				$y=0;	
			}
		}
		$data1['schedule_maxstep']=max($maxtimes);
		return M('meeting_roomschedule','','DB_MEETING')->where('schedule_id='.$rs[0]['schedule_id'])->save($data1);
	}
/**
  *拼写相关的数字
  *update author: zhanghao
  *update time  : 2014-11-28 11:28
  *use    this	: $this->schedule_meeting_room
  ****************************************/	
	public function init_nums($time){
		switch($time){
			case '08:00':$num=0;break;
			case '08:30':$num=1;break;
			case '09:00':$num=2;break;
			case '09:30':$num=3;break;
			case '10:00':$num=4;break;
			case '10:30':$num=5;break;
			case '11:00':$num=6;break;
			case '11:30':$num=7;break;
			case '12:00':$num=8;break;
			case '12:30':$num=9;break;
			case '13:00':$num=10;break;
			case '13:30':$num=11;break;
			case '14:00':$num=12;break;
			case '14:30':$num=13;break;
			case '15:00':$num=14;break;
			case '15:30':$num=15;break;
			case '16:00':$num=16;break;
			case '16:30':$num=17;break;
			case '17:00':$num=18;break;
			case '17:30':$num=19;break;
			case '18:00':$num=20;break;
			case '18:30':$num=21;break;
			case '19:00':$num=22;break;
			case '19:30':$num=23;break;
			case '20:00':$num=24;break;
		}
		return $num;
	}

	public function get_meeting_local($room_id)
	{
		$sql   = 'select * from meeting_room as b';
		$sql  .= ' join meeting_roomfloor c on b.floor_id=c.floor_id';
		$sql  .= ' join meeting_roombuilding d on c.building_id=d.building_id';
		$sql  .= ' join meeting_roomlocal e on d.local_id=e.local_id';
		$sql  .= ' where room_id='.$room_id;
		$rs    = M('meeting_room','','DB_MEETING')->query($sql);
		return $rs[0]['local_name'].' '.$rs[0]['building_name'].' '.$rs[0]['floor_name'].' '.$rs[0]['room_name'];
	}
}